package cn.turing.firecontrol.server.modbus;

import cn.turing.firecontrol.server.modbus.DeviceSensorDao;
import cn.turing.firecontrol.server.modbus.DeviceSensor;
import cn.turing.firecontrol.server.modbus.ModbusRTUOp;
import cn.turing.firecontrol.server.modbus.SerialPortMgmt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/modbus")
public class ModbusController {
    @Autowired
    DeviceSensorDao deviceSensorDao;

    @ResponseBody
    @RequestMapping("/continueRead")
    public void continueRead() throws Exception{
        //1.初始化连接处理
        ModbusRTUOp modbusRTUOp=new ModbusRTUOp();
        //虚拟设备地理信息
        DeviceSensor deviceSensor=new DeviceSensor();
        deviceSensor.setBuildingId(111);
        deviceSensor.setChannelId(1);
        deviceSensor.setSensorTypeId(1);
        deviceSensor.setCdId(111);
        deviceSensor.setFieldStatus("1");
        deviceSensor.setStatus("2");
        deviceSensor.setSensorNo("QVFTRVTMUAOP");
        deviceSensor.setFloor(1);
        deviceSensor.setPositionDescription("展厅");
        deviceSensor.setPositionSign(null);
        deviceSensor.setDelFlag("0");
        deviceSensor.setCrtUserName("admin");
        deviceSensor.setCrtUserId("1");
        deviceSensor.setCrtTime(new Date());
        deviceSensor.setUpdUserName("admin");
        deviceSensor.setUpdUserId("1");
        deviceSensor.setUpdTime(new Date());
        deviceSensor.setDepartId(null);
        deviceSensor.setTenantId("ac88ceb386aa4231b09bf472cb937c24");
        deviceSensor.setStatusTime(new Date());
        deviceSensor.setHydrantId(null);
        //初始化
        ModbusRTUOp.init();
        while(true){
            try{
                short[] data = ModbusRTUOp.batchReadHoldingRegisters(ModbusRTUOp.SLAVE_ADDRESS,0x0B, 1);  //index从0开始，对应100
                System.out.println(""+data[0]);
                //设置Status
                if (data[0] <= 5)
                    deviceSensor.setStatus("2");  //正常
                else
                    deviceSensor.setStatus("1");  //报警
            }catch (Exception ex){
                deviceSensor.setStatus("3");  //故障
                System.out.println(ex.getMessage());
            }finally {
                //插入数据库
                deviceSensorDao.insert(deviceSensor);
            }

            //下一阶段
            Thread.sleep(100);
        }

    }
}
